package com.project.harmonyledger.controller.oss;

import com.project.harmonyledger.common.response.Result;
import com.project.harmonyledger.common.response.ResultCode;
import com.project.harmonyledger.service.oss.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/file")
public class FileController {

  @Autowired
  private FileService fileService;

  /**
   * 单文件上传
   */
  @PostMapping("/upload")
  public Result<Map<String, String>> upload(@RequestPart("file") MultipartFile file) {
    Map<String, String> map = new HashMap<>();
    try {
      String fileUrl = fileService.upload(file);
      if (fileUrl != null && !fileUrl.isEmpty()) {
        map.put("url", fileUrl);
        return Result.success(map);
      } else {
        map.put("message", "文件上传失败");
        return Result.error(ResultCode.UPLOAD_FAILED, map);
      }
    } catch (Exception e) {
      log.error("文件上传失败: {}", e.getMessage());
      map.put("message", e.getMessage());
      return Result.error(ResultCode.SYSTEM_ERROR, map);
    }
  }

  /**
   * 多文件上传
   */
  @PostMapping("/uploads")
  public Result<Map<String, Object>> uploadBatch(@RequestPart("files") MultipartFile[] files) {
    Map<String, Object> map = new HashMap<>();
    try {
      List<String> urls = new ArrayList<>();
      List<String> failedFiles = new ArrayList<>();

      for (MultipartFile file : files) {
        try {
          String fileUrl = fileService.upload(file);
          if (fileUrl != null && !fileUrl.isEmpty()) {
            urls.add(fileUrl);
          } else {
            failedFiles.add(file.getOriginalFilename());
          }
        } catch (Exception e) {
          log.error("文件 {} 上传失败: {}", file.getOriginalFilename(), e.getMessage());
          failedFiles.add(file.getOriginalFilename());
        }
      }

      map.put("urls", urls);
      if (!failedFiles.isEmpty()) {
        map.put("failedFiles", failedFiles);
        return Result.error(ResultCode.PARTIAL_UPLOAD_FAILED, map);
      }
      return Result.success(map);

    } catch (Exception e) {
      log.error("批量文件上传失败: {}", e.getMessage());
      map.put("message", e.getMessage());
      return Result.error(ResultCode.SYSTEM_ERROR, map);
    }
  }
}
